'use strict';

var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var config = require('../config/config');

var sequelize = new Sequelize(
  config.mysql.database,
  config.mysql.user,
  config.mysql.pw, {
    host: config.mysql.host,
    dialect: 'mysql',
    port: config.mysql.port || '3306'
  });


var sequelizeService = {};
sequelizeService.Sequelize = Sequelize;
sequelizeService.sequelize = sequelize;

sequelizeService.models = {};

var modelpath = path.join(__dirname, '../models');

fs
  .readdirSync(modelpath)
  .filter(function(file) {
    return (file.indexOf('.js') !== -1);
  })
  .forEach(function(file) {
    var model = sequelize.import(path.join(modelpath, file));
    sequelizeService.models[model.name] = model;
  });

Object.keys(sequelizeService.models).forEach(function(modelName) {
  if ('associate' in sequelizeService.models[modelName]) {
    sequelizeService.models[modelName].associate(sequelizeService.models);
  }
});

module.exports = sequelizeService;
